package tix

import java.io.File

/** Workflow for autotools-based packages */
class AutotoolsWorkflow(val pkg: itf.AutotoolsPackageVersion) extends itf.AutotoolsPackageWorkflow {
  override def install(): Unit = {
    setupSource()
    configure()
    make()
    makeInstall()
    clean()
  }

  override def remove {
    throw new RuntimeException("Not implemented")
  }

  def setupSource() {
    val source: File = Global.locateSource(pkg.sourcePackage)
    assert(source.exists())

    if (pkg.sourceDir.exists()) {
      new Command(cmd = List("rm", "-rf", pkg.sourceDir.getAbsolutePath()),
        cwd = Some(pkg.sourceDir))
    }
    assert(pkg.sourceDir.mkdirs())
    assert(pkg.sourceDir.exists())

    // TODO: Handle all archive types (eg. zip)
    new Command(cmd = List("tar",
      "xf", source.getAbsolutePath(),
      "-C", pkg.sourceDir.getAbsolutePath(),
      "--strip-components", "1"))
  }

  def configure() {
    assert(pkg.sourceDir.exists())
    val configure = new File(pkg.sourceDir, "configure")
    assert(configure.exists(), "File missing %s" format configure)

    if (!pkg.buildDir.exists())
      assert(pkg.buildDir.mkdirs(), "Cannot make directory %s" format pkg.buildDir)
    assert(pkg.buildDir.exists())

    new Command(cmd = List(configure.getAbsolutePath(),
      "--prefix=" + pkg.installDir.getAbsolutePath())
      ++ pkg.configureFlags(),
      cwd = Some(pkg.buildDir))
  }

  def make() {
    new Command(cmd = List("make", "--jobs=" + Global.njobs),
      cwd = Some(pkg.buildDir))
  }

  def makeInstall() {
    new Command(cmd = List("make", "install", "--jobs=" + Global.njobs),
      cwd = Some(pkg.buildDir),
      logPrefix = Some("make_install"))
  }

  def clean() {
    return
    new Command(cmd = List("make", "clean", "--jobs=" + Global.njobs),
      cwd = Some(pkg.buildDir),
      logPrefix = Some("make_clean"))
    new Command(cmd = List("rm", "-rf", pkg.buildDir.getAbsolutePath()),
      cwd = Some(pkg.buildDir))
  }
}
